package com.shanzmoo.h5.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.db.personnel.entity.WechatConfigData;
import com.shanzmoo.h5.domain.bo.WxAuthAccessTokenBO;
import com.shanzmoo.h5.service.IWechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 微信服务实现类
 * @author Gzhao 2020/12/26
 */
@Slf4j
@Service
public class WechatServiceImpl implements IWechatService {

    @Override
    public SResponse<WxAuthAccessTokenBO> getWxAuthAccessToken(String code) {
        String url = WechatConfigData.QUTHORIZE_URL
                + "?appid=" + WechatConfigData.appId
                + "&secret=" + WechatConfigData.appSecret
                + "&code=" + code
                + "&grant_type=authorization_code";

        String response= HttpUtil.get(url);
        log.info("请求access_token结果：{}", response);

        JSONObject resultJson = JSON.parseObject(response);

        if (ObjectUtil.isNotEmpty(resultJson.get("errcode"))){
            Integer errcode = (Integer)resultJson.get("errcode");
            String errmsg = (String)resultJson.get("errmsg");

            log.error("获取微信网页授权 access_token 失败，返回结果：{}", resultJson);
            return SResponse.fail(Constant.ERRCODE_LOGIC, "获取网页授权access_token失败, errcode: " + errcode
                    + ", errmsg: " + errmsg);
        }
        WxAuthAccessTokenBO accessTokenBO = JSON.parseObject(resultJson.toJSONString(), WxAuthAccessTokenBO.class);

        return SResponse.ok(accessTokenBO);
    }

}
